/**********************************************************************************
 * Copyright (c) 2012 - 2012,  parallel, All right reserved
 * Title: com.adc.parallel.control  ParallelController.java 
 * @author shen  shenqiao2012@163.com 
 *  2012-11-22 下午12:25:45 
 *********************************************************************************/


package com.adc.parallel.control;


import com.adc.litepool.ObjectPoolHandler;
import com.adc.parallel.constants.CompleteList;
import com.adc.parallel.constants.ReceiveList;
import com.adc.parallel.constants.RuntimeList;
import com.adc.parallel.constants.SysConstants;
import com.adc.parallel.constants.ThreadConstant;
import com.adc.parallel.constants.WaitList;
import com.adc.parallel.daemon.ExecutorDaemonThread;
import com.adc.parallel.daemon.MainDaemonThread;
import com.adc.parallel.dto.BaseTaskDto;
import com.adc.parallel.pool.BaseExecutorThread;
import com.adc.parallel.pool.ThreadPool;


/**
 * 
 * Description: parallel process main thread
 * @author shen  shenqiao2012@163.com 
 * @param <T>
 * @param <E>
 * @param <S>
 */
@SuppressWarnings("unchecked")
public class ParallelController<T extends BaseExecutorThread<E , S>, 
                                E extends BaseTaskDto<S>, S> extends Thread{
	private ObjectPoolHandler pool;
	private T t;
	/** 
	 *     
	 */
	public ParallelController(T t) {
		// TODO Auto-generated constructor stub
		this.t=t;
	}
	
	/**
	 * Description:  
	 * @see java.lang.Thread#run() 
	 */
	@Override
	public void run() {
		if (t!=null) {
			InitGlobalVariable.init();
			new MainDaemonThread().start(); //  check exit or not! start daemon if not first time
			//		System.out.println(InitGlobalVariable.getReceiveDaemonThread().getName());
			pool = ThreadPool.getPoolHandler(t);
			
			while (!SysConstants.isExitMain()) {
				int num=pool.getMaxNum() - pool.getIdleNum();
				System.err.println("Resouse for use:" + num+"\tIdle:"+pool.getIdleNum()+"\tActive:"+pool.getActiveNum());
				System.err.println("\tRE:"+ReceiveList.getReceiveList().size()+"\tWT:"+
						WaitList.getWaitList().size()+"\tRT:"+RuntimeList.getRuntimeList().size()+"\tCP:"+
						CompleteList.getCompleteList().size());
				if (WaitList.getWaitList().size()>0) {
					while (num > -1) { // if pool has idle size
						T executorThread = (T) pool.borrowObject();
						E taskDto = (E) WaitList.getFirstTaskDto();
						if (taskDto!=null) {
							ExecutorDaemonThread<T, E, S> executorDaemonThread = new ExecutorDaemonThread<T, E, S>(
									executorThread, taskDto);
							executorDaemonThread.start();
						}
						if (WaitList.getWaitList().size()==0) {
							break;
						}
					}
				}
				try {
					sleep(ThreadConstant.getMainSleepTime());
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
